package me.sealer.aop;

import me.sealer.annotation.Action;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.lang.reflect.Method;

/**
 * Created by sealer on 09-09-2017.
 */
@Aspect
@Component
public class LogAspect {

    Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(me.sealer.annotation.Action)")
    public void actionAnnotationPointCut() {
    }

    @After("actionAnnotationPointCut()")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        logger.info(method.getName());
        Action action = method.getAnnotation(Action.class);
        logger.info("注解式拦截： " + (action == null ? "action is null" : action.value()));
    }

    @Before("execution(* me.sealer.controller.FunctionController.*(..))")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        logger.info("方法规则拦截： " + method.getName());
    }

    @PostConstruct
    public void init() {
        logger.info(LogAspect.class.getSimpleName() + " is constricted");
    }

    @PreDestroy
    public void destroy() {
        logger.info(LogAspect.class.getSimpleName() + " is destroyed");
    }
}
